/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.service.loader.internal;

import lombok.NoArgsConstructor;
import org.apache.commons.beanutils.PropertyUtils;
import org.jrose.api.annotation.remote.ExposeHttpService;
import org.jrose.entity.data.User;
import org.jrose.service.loader.AbstractLoader;
import org.jrose.service.loader.TeamLoader;
import org.jrose.service.loader.UserLoader;

import javax.inject.Named;

import static org.jrose.entity.constant.UserType.PLAYER;

/**
 * Default {@link UserLoader} implementation.
 *
 * @author Xiaohai Zhang
 * @see TeamLoader
 * @since 2013-08-26 10:30
 */
@Named
@NoArgsConstructor
@ExposeHttpService(name = "/userLoader", serviceInterface = UserLoader.class)
public class UserLoaderImpl extends AbstractLoader implements UserLoader {
    @Override
    public User transform(User source) {
        if (source == null) {
            return null;
        }
        User destination = source;

        if (source.getUserType() == PLAYER) {
            destination = new User();
            try {
                PropertyUtils.copyProperties(destination, source);
            } catch (Exception ex) {
                throw new RuntimeException(ex.getMessage(), ex);
            }
            TeamLoader teamLoader = getBean(TeamLoader.class);
            destination.setTeam(teamLoader.loadUserTeam(destination));
        }
        return destination;
    }

    @Override
    public User loadByUsername(String username) {
        if (username == null) {
            return null;
        }
        return transform(userPersistence.findByUsername(username));
    }
}
